// 闲置物品登记页面逻辑
const NeighborhoodAPI = require('../../../js/services/api/neighborhoodService');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      itemName: '',
      itemDesc: '',
      contactInfo: '',
      borrowCondition: ''
    },
    errors: {},
    categoryOptions: ['工具类', '电器类', '家具类', '运动器材', '其他'],
    selectedCategory: -1,
    durationOptions: [
      { label: '1天', value: 1 },
      { label: '3天', value: 3 },
      { label: '1周', value: 7 },
      { label: '2周', value: 14 },
      { label: '1个月', value: 30 }
    ],
    selectedDuration: -1,
    imageUrl: '',
    isSubmitting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('页面加载 - 闲置物品登记');
    wx.setNavigationBarTitle({
      title: '闲置物品登记'
    });
    this.initFormData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('页面显示 - 闲置物品登记');
    this.initFormData();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('下拉刷新');
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('触底');
  },

  /**
   * 初始化表单数据
   */
  initFormData: function() {
    this.setData({
      formData: {
        itemName: '',
        itemDesc: '',
        contactInfo: '',
        borrowCondition: ''
      },
      errors: {},
      selectedCategory: -1,
      selectedDuration: 0,
      imageUrl: '',
      isSubmitting: false
    });
    
    console.log('闲置物品登记页面数据初始化完成:', this.data);
  },

  /**
   * 输入框变化处理
   */
  onInputChange: function(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    console.log('闲置物品输入变化:', field, value);
    
    this.setData({
      [`formData.${field}`]: value
    });
    
    // 清除对应字段的错误信息
    if (this.data.errors[field]) {
      this.setData({
        [`errors.${field}`]: ''
      });
    }
  },

  /**
   * 选择物品类别
   */
  onCategoryChange: function(e) {
    this.setData({
      selectedCategory: e.detail.value
    });
    
    // 清除错误信息
    if (this.data.errors.itemCategory) {
      this.setData({
        'errors.itemCategory': ''
      });
    }
  },

  /**
   * 选择借用时长
   */
  onDurationChange: function(e) {
    this.setData({
      selectedDuration: e.detail.value
    });
    
    // 清除错误信息
    if (this.data.errors.borrowDuration) {
      this.setData({
        'errors.borrowDuration': ''
    });
    }
  },

  /**
   * 选择图片
   */
  chooseImage: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          imageUrl: res.tempFilePaths[0]
        });
      }
    });
  },

  /**
   * 表单验证
   */
  validateForm: function() {
    const errors = {};
    const { formData, selectedCategory, selectedDuration } = this.data;
    
    if (!formData.itemName.trim()) {
      errors.itemName = '请输入物品名称';
    }
    
    if (selectedCategory < 0) {
      errors.itemCategory = '请选择物品类别';
    }
    
    if (selectedDuration < 0) {
      errors.borrowDuration = '请选择借用时长';
    }
    
    if (!formData.contactInfo.trim()) {
      errors.contactInfo = '请输入联系方式';
    } else if (!/^1[3-9]\d{9}$/.test(formData.contactInfo)) {
      errors.contactInfo = '请输入正确的手机号码';
    }
    
    this.setData({ errors });
    return Object.keys(errors).length === 0;
  },

  /**
   * 提交物品登记
   */
  submitItem: function(e) {
    if (this.data.isSubmitting) return;

    // 表单验证
    if (!this.validateForm()) {
      return;
    }

    this.setData({ isSubmitting: true });
    
    // 构建提交数据
    const submitData = {
      itemName: this.data.formData.itemName.trim(),
      itemCategory: this.data.categoryOptions[this.data.selectedCategory],
      itemDesc: this.data.formData.itemDesc.trim(),
      borrowDuration: this.data.durationOptions[this.data.selectedDuration].value,
      contactInfo: this.data.formData.contactInfo.trim(),
      borrowCondition: this.data.formData.borrowCondition.trim(),
      imageUrl: this.data.imageUrl || ''
    };

    NeighborhoodAPI.registerIdleItem(submitData)
      .then(res => {
        if (res.success) {
          wx.showToast({ 
            title: '物品登记成功，等待审核', 
            icon: 'success',
            duration: 2000
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        } else {
          wx.showToast({ title: res.message || '登记失败', icon: 'none' });
        }
      })
      .catch(err => {
        console.error('物品登记失败:', err);
        wx.showToast({ title: '网络异常，登记失败', icon: 'none' });
      })
      .finally(() => {
        this.setData({ isSubmitting: false });
      });
  }
});